﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using Caliburn.Micro;
using Microsoft.Phone.Tasks;
using Wulong.Phone.Dianping.Constants;
using Wulong.Phone.Dianping.Helpers;
using Wulong.Phone.Dianping.Models;
using Wulong.Phone.Dianping.Services;

namespace Wulong.Phone.Dianping.ViewModels
{
    public class MerchantPivotViewModel : 
        PaginationViewModelBase, 
        IHandle<TaskCompleted<PhoneCallTask>>
    {
        private IDisposable _disposable;
        private readonly IEventAggregator _events;
        private readonly IWindowManager _window;
        public MerchantPivotViewModel(
            IEventAggregator events,
            IWindowManager window)
        {
            _events = events;
            _window = window;
            _merchant = new Merchant();
            _reviews = new ObservableCollection<Review>();
            CanLoadMore = true;
            if (Page < 1)
                Page = 1;
        }

        protected override void OnViewReady(object view)
        {
            base.OnViewReady(view);
            DianpingService.ObservableMerchantItem(CityCode, MerchantId)
                .ObserveOnDispatcher()
                .Subscribe(item =>
                               {
                                   Merchant = item;
                                   Merchant.ImageUrl = ImageUrl;
                                   Merchant.Id = MerchantId;
                                   Merchant.AvgPrice = MerchantAvgPrice;
                                   Merchant.OverallRating = MerchantOverallRating;
                                   NotifyOfPropertyChange(()=>Merchant);
                                   NotifyOfPropertyChange(() => MapUrl);
                               });
            Load();
            
        }

        public string MapUrl
        {
            get { return string.IsNullOrWhiteSpace(Merchant.Addr)
                ?
                null:
                string.Format(
                CommonConstants.BaiduMapUrl, 
                DianpingService.GetCity(CityCode).Name, 
                Merchant.Addr); }
        }

        private void Load()
        {
            IsBusy = true;
            CanLoadMore = false;
            _disposable=DianpingService.ObservableReview(MerchantId, CityCode)
                .ObserveOnDispatcher()
                .Finally(() => IsBusy = false)
                .Subscribe(item => _reviews.Add(item),
                           error => MessageHelper.ShowErrorMessage(),
                    () =>
                    {
                        CanLoadMore = _reviews.Count > 0;
                    });
        }

        public void LoadMore()
        {
            IsBusy = true;
            CanLoadMore = false;
            _disposable=DianpingService.ObservableReview(MerchantId, CityCode, ++Page)
                .ObserveOnDispatcher()
                .Finally(() => IsBusy = false)
                .Subscribe(item => _reviews.Add(item),
                           error =>
                               {
                                   MessageHelper.ShowErrorMessage();
                                   --Page;
                               },
                    () =>
                    {
                        CanLoadMore = _reviews.Count > 0;
                    });
        }

// ReSharper disable InconsistentNaming
        internal ObservableCollection<Review> _reviews;
// ReSharper restore InconsistentNaming
        public IEnumerable<Review> Reviews
        {
            get { return _reviews; }
        }
        private Merchant _merchant;
        public Merchant Merchant
        {
            get { return _merchant; }
            set
            {
                _merchant = value;
                NotifyOfPropertyChange(()=>Merchant);
            }
        }

        private Review _selectedReview;
        public Review SelectedReview
        {
            get { return _selectedReview; }
            set
            {
                _selectedReview = value;
                NotifyOfPropertyChange(()=>SelectedReview);
            }
        }

        public string MerchantId { get; set; }
        public string ImageUrl { get; set; }
        public string MerchantOverallRating
        { get; set; }

        public string MerchantAvgPrice
        { get; set; }
        public void MakePhoneCall()
        {
            _events.RequestTask<PhoneCallTask>(
                x=>
                    {
                        x.DisplayName = Merchant.Name;
                        x.PhoneNumber = Merchant.Tel;
                    });
        }

        public void ReadReview()
        {
            if(SelectedReview == null) return;
            var vm = new ReviewDialogViewModel(SelectedReview.FullReviewLink);
            _window.ShowDialog(vm);
            SelectedReview = null;
        }

        public void Handle(TaskCompleted<PhoneCallTask> message)
        {
            
        }

        protected override void OnDeactivate(bool close)
        {
            base.OnDeactivate(close);
            if(_disposable!=null)
                _disposable.Dispose();
        }
    }
}
